import 'package:enjoy_plus/models/tab_bar_model.dart';
import 'package:enjoy_plus/pages/kuan/kuan.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';
import 'package:enjoy_plus/pages/mine/mine.dart';

import 'home/index.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  int currentIndex = 0;

  List<TabBarItem> tabBarList = [
    const TabBarItem(
      title: "首页",
      defaultIcon: "assets/tabs/home_default.png",
      activeIcon: "assets/tabs/home_active.png",
    ),
    const TabBarItem(
      title: "我的",
      defaultIcon: "assets/tabs/my_default.png",
      activeIcon: "assets/tabs/my_active.png",
    ),
    const TabBarItem(
      title: "酷安",
      defaultIcon: "assets/tabs/home_default.png",
      activeIcon: "assets/tabs/home_active.png",
    )
  ];

  @override
  void initState() {
    super.initState();
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: [
            HomePage(),
            MinePage(currentIndex: currentIndex),
            KuAnPage(),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        items: barItemList(),
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        backgroundColor: Colors.white,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(BottomNavigationBarItem(
        icon: Image.asset(
          item.defaultIcon,
          width: 32,
          height: 32,
        ),
        activeIcon: Image.asset(
          item.activeIcon,
          width: 32,
          height: 32,
        ),
        label: item.title,
      ));
    }
    return items;
  }
}
